<template>
  <div class="document-container">
    <el-card class="document-card">
      <template #header>
        <div class="card-header">
          <h3>案件文档管理</h3>
          <el-button type="primary" @click="handleAdd">上传文档</el-button>
        </div>
      </template>

      <el-form :model="queryForm" :inline="true" @submit.prevent="handleQuery">
        <el-form-item label="案件编号">
          <el-input v-model="queryForm.case_code" placeholder="请输入案件编号" clearable />
        </el-form-item>
        <el-form-item label="文档类型">
          <el-select
            v-model="queryForm.doc_type"
            placeholder="请选择文档类型"
            clearable
            style="width: 120px"
          >
            <el-option label="起诉状" value="1" />
            <el-option label="答辩状" value="2" />
            <el-option label="代理词" value="3" />
            <el-option label="判决书" value="4" />
            <el-option label="裁定书" value="5" />
            <el-option label="调解书" value="6" />
            <el-option label="证据材料" value="7" />
            <el-option label="其他" value="8" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="documentList" border stripe v-loading="loading" row-key="id">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="case_code" label="案件编号" min-width="280" />
        <el-table-column prop="title" label="标题" min-width="180" />
        <el-table-column prop="doc_type" label="类型" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.doc_type === '1'">起诉状</el-tag>
            <el-tag v-else-if="row.doc_type === '2'">答辩状</el-tag>
            <el-tag v-else-if="row.doc_type === '3'">代理词</el-tag>
            <el-tag v-else-if="row.doc_type === '4'">判决书</el-tag>
            <el-tag v-else-if="row.doc_type === '5'">裁定书</el-tag>
            <el-tag v-else-if="row.doc_type === '6'">调解书</el-tag>
            <el-tag v-else-if="row.doc_type === '7'">证据材料</el-tag>
            <el-tag v-else-if="row.doc_type === '8'">其他</el-tag>
            <el-tag v-else>未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="upload_user" label="上传人" width="120" />
        <el-table-column prop="create_time" label="上传时间" width="160" />
        <el-table-column prop="file_count" label="文件数" width="100">
          <template #default="{ row }">
            {{ row.file_count || 0 }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" class="view-btn" @click="handleViewDetail(row)">
              查看详情
            </el-button>
            <el-button
              v-if="isSuperAdmin || isDocumentCreator(row)"
              type="danger"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="queryForm.page"
        v-model:page-size="queryForm.limit"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 上传文档对话框 -->
    <el-dialog v-model="dialogVisible" title="上传案件文档" width="600px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="案件编号" prop="case_code">
          <el-input v-model="form.case_code" placeholder="请输入案件编号" />
        </el-form-item>
        <el-form-item label="文档标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文档标题" />
        </el-form-item>
        <el-form-item label="文档类型" prop="doc_type">
          <el-select v-model="form.doc_type" placeholder="请选择文档类型" style="width: 120px">
            <el-option label="起诉状" value="1" />
            <el-option label="答辩状" value="2" />
            <el-option label="代理词" value="3" />
            <el-option label="判决书" value="4" />
            <el-option label="裁定书" value="5" />
            <el-option label="调解书" value="6" />
            <el-option label="证据材料" value="7" />
            <el-option label="其他" value="8" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传文件" prop="file">
          <el-upload
            class="upload-demo"
            action="/upload"
            :limit="1"
            :auto-upload="false"
            :on-change="handleFileChange"
          >
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">只能上传doc/docx/pdf文件，且不超过10MB</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 文档详情抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      :title="currentDocument?.title || '文档详情'"
      direction="rtl"
      size="60%"
      class="document-detail-drawer"
    >
      <div v-if="currentDocument" class="document-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="案件编号">
            {{ currentDocument.case_code }}
          </el-descriptions-item>
          <el-descriptions-item label="文档标题">{{ currentDocument.title }}</el-descriptions-item>
          <el-descriptions-item label="文档类型">
            <el-tag v-if="currentDocument.doc_type === '1'">起诉状</el-tag>
            <el-tag v-else-if="currentDocument.doc_type === '2'">答辩状</el-tag>
            <el-tag v-else-if="currentDocument.doc_type === '3'">代理词</el-tag>
            <el-tag v-else-if="currentDocument.doc_type === '4'">判决书</el-tag>
            <el-tag v-else-if="currentDocument.doc_type === '5'">裁定书</el-tag>
            <el-tag v-else-if="currentDocument.doc_type === '6'">调解书</el-tag>
            <el-tag v-else-if="currentDocument.doc_type === '7'">证据材料</el-tag>
            <el-tag v-else-if="currentDocument.doc_type === '8'">其他</el-tag>
            <el-tag v-else>未知</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="上传人">
            {{ currentDocument.upload_user }}
          </el-descriptions-item>
          <el-descriptions-item label="上传时间">
            {{ currentDocument.create_time }}
          </el-descriptions-item>
          <el-descriptions-item label="文件数量">
            {{ currentDocument.file_count || 0 }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="file-section">
          <div class="section-header">
            <h4>文件列表</h4>
            <el-button type="primary" size="small" @click="handleAddFile">添加文件</el-button>
          </div>

          <el-table :data="currentDocument.file_list" border v-loading="fileLoading">
            <el-table-column prop="name" label="文件名称" min-width="200" />
            <el-table-column prop="file_size_text" label="文件大小" width="100" />
            <el-table-column prop="file_ext" label="文件类型" width="80" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row: fileRow }">
                <el-button type="primary" link @click.stop="handleFilePreview(fileRow)">
                  预览
                </el-button>
                <el-button type="success" link @click.stop="handleFileDownload(fileRow)">
                  下载
                </el-button>
                <el-button
                  v-if="isSuperAdmin || isFileCreator(fileRow)"
                  type="danger"
                  link
                  @click.stop="handleFileDelete(fileRow)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <div
            v-if="!currentDocument.file_list || currentDocument.file_list.length === 0"
            class="empty-file"
          >
            <el-empty description="暂无文件" />
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 文件预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="文件预览"
      width="80%"
      top="5vh"
      @closed="handlePreviewClosed"
    >
      <div class="file-preview">
        <div v-if="previewFile" class="preview-info">
          <p>
            <strong>文件名：</strong>
            {{ previewFile.name }}
          </p>
          <p>
            <strong>文件大小：</strong>
            {{ previewFile.file_size_text }}
          </p>
          <p>
            <strong>文件类型：</strong>
            {{ previewFile.file_ext }}
          </p>
        </div>
        <div class="preview-content" v-loading="previewLoading">
          <!-- PDF文件预览 -->
          <iframe
            v-if="
              previewFile &&
              (previewFile.file_ext === 'pdf' || previewFile.file_ext === 'PDF') &&
              previewUrl
            "
            :src="previewUrl"
            width="100%"
            height="600px"
            frameborder="0"
            @error="handlePreviewError"
          ></iframe>
          <!-- 图片文件预览 -->
          <div
            v-else-if="previewFile && isImageFile(previewFile.file_ext) && previewUrl"
            class="image-preview"
          >
            <img
              :src="previewUrl"
              :alt="previewFile.name"
              style="max-width: 100%; max-height: 600px"
              @error="handlePreviewError"
            />
          </div>
          <!-- 文本文件预览 -->
          <div v-else-if="previewFile && isTextFile(previewFile.file_ext)" class="text-preview">
            <el-input
              type="textarea"
              :rows="20"
              readonly
              placeholder="正在加载文本内容..."
              v-model="textPreviewContent"
            ></el-input>
          </div>
          <!-- 不支持预览的文件类型 -->
          <div v-else class="no-preview">
            <el-empty description="该文件类型不支持预览" />
            <el-button type="primary" @click="handleFileDownload(previewFile!)">下载文件</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import request from '@/utils/request'
  import { ref, reactive, onMounted, computed } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { useLawcaseStore } from '../../store/lawcase'
  import { useUserStore } from '../../store/user'
  import {
    deleteCaseDoc,
    uploadCaseDoc,
    downloadCaseDoc,
    viewCaseDoc,
  } from '../../services/lawcase'
  import { deleteFile as deleteFileApi } from '../../api/home/files'

  /**
   * 格式化日期函数
   * 处理各种日期格式和时间戳，确保返回有效日期字符串或空字符串
   */
  const formatDate = (dateInput: any): string => {
    if (!dateInput) return ''

    let date
    // 处理不同类型的日期输入
    if (typeof dateInput === 'number') {
      // 判断是秒级时间戳还是毫秒级时间戳
      date = dateInput.toString().length > 10 ? new Date(dateInput) : new Date(dateInput * 1000)
    } else if (typeof dateInput === 'string') {
      // 如果是字符串，尝试直接解析
      date = new Date(dateInput)
    } else {
      // 其他类型，直接使用
      date = dateInput
    }

    // 验证日期是否有效
    if (isNaN(date.getTime())) {
      return ''
    }

    // 格式化日期为 YYYY-MM-DD HH:mm:ss 格式
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }

  // 定义文档类型
  interface FileItem {
    id: number
    name: string
    filepath: string
    file_size: number
    file_size_text?: string
    file_ext?: string
    user_id?: number
  }

  interface DocumentItem {
    id: number
    case_code: string
    title: string
    doc_type: string
    upload_user: string
    upload_uid: number
    create_time: string
    file_count?: number
    file_list?: FileItem[]
  }

  // 数据列表
  const documentList = ref<DocumentItem[]>([])
  const loading = ref(false)
  const total = ref(0)
  const fileLoading = ref(false)

  // 查询表单
  const queryForm = reactive({
    page: 1,
    limit: 10,
    case_code: '',
    doc_type: '',
  })

  // 对话框
  const dialogVisible = ref(false)
  const drawerVisible = ref(false)
  const previewVisible = ref(false)

  // 当前选中的文档
  const currentDocument = ref<DocumentItem | null>(null)
  const previewFile = ref<FileItem | null>(null)
  const textPreviewContent = ref('')

  // 预览URL
  const previewUrl = ref('')
  const previewLoading = ref(false)

  // 处理预览关闭
  const handlePreviewClosed = () => {
    // 释放blob URL以避免内存泄漏
    if (previewUrl.value) {
      URL.revokeObjectURL(previewUrl.value)
      previewUrl.value = ''
    }
    // 清空文本预览内容
    textPreviewContent.value = ''
  }

  // 处理文件预览
  const handleFilePreview = async (file: FileItem) => {
    previewFile.value = file
    previewVisible.value = true
    previewLoading.value = true

    try {
      // 对于PDF和图片文件，使用fetch获取文件内容并创建blob URL
      if (file.file_ext === 'pdf' || file.file_ext === 'PDF' || isImageFile(file.file_ext)) {
        const response = await request({
          url: `/api/lawcase/casedocs/preview?file_id=${file.id}`,
          method: 'GET',
          responseType: 'blob',
        })

        // 创建blob URL
        const blob = new Blob([response.data], { type: response.headers['content-type'] })
        previewUrl.value = URL.createObjectURL(blob)
      }
      // 对于文本文件，获取文本内容
      else if (isTextFile(file.file_ext)) {
        const response = await request({
          url: `/api/lawcase/casedocs/preview?file_id=${file.id}`,
          method: 'GET',
        })

        textPreviewContent.value = response.data || '文件内容为空'
      }
    } catch (error) {
      console.error('预览文件失败:', error)
      ElMessage.error('预览文件失败')
    } finally {
      previewLoading.value = false
    }
  }

  // 表单数据
  const form = reactive({
    id: 0,
    case_code: '',
    title: '',
    doc_type: '',
    file: null as File | null,
  })

  // 表单验证规则
  const rules = {
    case_code: [{ required: true, message: '请输入案件编号', trigger: 'blur' }],
    title: [{ required: true, message: '请输入文档标题', trigger: 'blur' }],
    doc_type: [{ required: true, message: '请选择文档类型', trigger: 'change' }],
  }

  // 表单引用
  const formRef = ref()

  // 初始化store
  const lawcaseStore = useLawcaseStore()
  const userStore = useUserStore()

  // 判断当前用户是否为超级管理员
  // 通过检查用户菜单中是否包含"系统管理"相关权限来判断
  const isSuperAdmin = computed(() => {
    const userInfo = userStore.userInfo
    if (!userInfo || !userInfo.menu) return false

    // 检查菜单中是否包含系统管理相关的权限项
    const menuItems = Array.isArray(userInfo.menu) ? userInfo.menu : []

    // 检查是否有系统管理相关的菜单项
    return menuItems.some((item: any) => {
      // 检查菜单名称或路径是否包含系统管理相关关键词
      const menuName = item.name || item.title || ''
      const menuPath = item.path || ''

      return (
        menuName.includes('系统管理') ||
        menuName.includes('用户管理') ||
        menuName.includes('角色管理') ||
        menuName.includes('权限管理') ||
        menuPath.includes('system') ||
        menuPath.includes('admin')
      )
    })
  })

  // 判断当前用户是否是文档创建人
  const isDocumentCreator = (row: DocumentItem) => {
    const userInfo = userStore.userInfo
    return userInfo && row.upload_uid === userInfo.id
  }

  // 判断当前用户是否是文件创建人
  const isFileCreator = (file: FileItem) => {
    const userInfo = userStore.userInfo
    return userInfo && file.user_id === userInfo.id
  }

  // 查询
  const handleQuery = () => {
    queryForm.page = 1
    console.log('查询参数:', queryForm)
    getDocumentList()
  }

  // 格式化文件大小
  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }

  // 获取文件扩展名
  const getFileExtension = (fileName: string): string => {
    if (!fileName) return ''
    const lastDotIndex = fileName.lastIndexOf('.')
    if (lastDotIndex === -1) return ''
    return fileName.substring(lastDotIndex + 1).toLowerCase()
  }

  // 判断是否为图片文件
  const isImageFile = (ext: string | undefined): boolean => {
    const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
    return imageExts.includes(ext?.toLowerCase() || '')
  }

  // 判断是否为文本文件
  const isTextFile = (ext: string | undefined): boolean => {
    const textExts = [
      'txt',
      'md',
      'json',
      'xml',
      'csv',
      'log',
      'html',
      'htm',
      'js',
      'css',
      'vue',
      'ts',
      'jsx',
      'tsx',
    ]
    return textExts.includes(ext?.toLowerCase() || '')
  }

  // 处理预览错误
  const handlePreviewError = () => {
    ElMessage.error('文件预览失败，请尝试下载文件查看')
  }

  // 获取数据列表（优化：使用后端返回的文件信息，无需重复请求）
  const getDocumentList = async () => {
    loading.value = true
    try {
      console.log('请求API参数:', {
        page: queryForm.page,
        limit: queryForm.limit,
        case_code: queryForm.case_code,
        doc_type: queryForm.doc_type,
      })

      const res = await lawcaseStore.getCaseDocListAction({
        page: queryForm.page,
        limit: queryForm.limit,
        case_code: queryForm.case_code,
        doc_type: queryForm.doc_type,
      })

      console.log('API响应:', res)
      if (res.code === 0) {
        // 直接使用后端返回的数据，无需额外请求详情
        documentList.value = res.data.map((item: any) => {
          // 优先使用后端预加载的文件列表
          const fileList: FileItem[] = (item.file_list || []).map((file: any) => ({
            id: file.id,
            name: file.name,
            filepath: file.filepath || file.path || '',
            file_size: Number(file.filesize || file.file_size) || 0,
            file_size_text:
              file.file_size_text || formatFileSize(Number(file.filesize || file.file_size) || 0),
            file_ext: file.file_ext || getFileExtension(file.name),
            user_id: file.user_id || 0,
          }))

          // 后端已经提供了文件数量
          const fileCount = item.file_count || fileList.length || 0

          return {
            id: item.id,
            case_code: item.case_code,
            title: item.title,
            doc_type: item.doc_type.toString(),
            upload_user: item.upload_user || item.uploader_name || item.uploader || '未知用户',
            upload_uid: item.upload_uid || 0,
            create_time: item.create_time_text || formatDate(item.create_time),
            file_count: fileCount,
            file_list: fileList,
          }
        })
        total.value = res.count || 0
      }
    } catch (error) {
      console.error('获取案件文档列表失败:', error)
      ElMessage.error('获取案件文档列表失败')
    } finally {
      loading.value = false
    }
  }

  // 重置
  const handleReset = () => {
    queryForm.case_code = ''
    queryForm.doc_type = ''
    queryForm.page = 1
    getDocumentList()
  }

  // 分页
  const handleSizeChange = (val: number) => {
    queryForm.limit = val
    getDocumentList()
  }

  const handleCurrentChange = (val: number) => {
    queryForm.page = val
    getDocumentList()
  }

  // 上传文档
  const handleAdd = () => {
    Object.assign(form, {
      id: 0,
      case_code: '',
      title: '',
      doc_type: '',
      file: null,
    })
    dialogVisible.value = true
  }

  // 查看文档详情
  const handleViewDetail = async (row: DocumentItem) => {
    currentDocument.value = row

    // 如果文件列表为空，尝试重新获取
    if (!row.file_list || row.file_list.length === 0) {
      fileLoading.value = true
      try {
        const detailRes = await lawcaseStore.getCaseDocDetail(row.id)
        if (detailRes.code === 0 && detailRes.data && detailRes.data.file_array) {
          const fileList = detailRes.data.file_array.map((file: any) => ({
            id: file.id,
            name: file.name,
            filepath: file.filepath,
            file_size: Number(file.filesize || file.file_size) || 0,
            file_size_text: formatFileSize(Number(file.filesize || file.file_size) || 0),
            file_ext: getFileExtension(file.name),
            user_id: file.user_id || 0,
          }))
          currentDocument.value.file_list = fileList
          currentDocument.value.file_count = fileList.length
        }
      } catch (error) {
        console.error('获取文档详情失败:', error)
        ElMessage.error('获取文档详情失败')
      } finally {
        fileLoading.value = false
      }
    }

    drawerVisible.value = true
  }

  // 添加文件
  const handleAddFile = () => {
    ElMessage.info('添加文件功能待实现')
  }

  // 文件变更处理
  const handleFileChange = (file: any) => {
    form.file = file.raw
  }

  // 下载单个文件
  const handleFileDownload = async (fileRow: FileItem) => {
    try {
      loading.value = true

      // 使用项目配置的request实例，这样会自动带上认证token
      const response = await request({
        url: `/api/lawcase/casedocs/download`,
        method: 'get',
        params: { file_id: fileRow.id },
        responseType: 'blob', // 设置响应类型为blob
      })

      // 从响应头中获取文件名
      const contentDisposition =
        response.headers['content-disposition'] || response.headers['Content-Disposition']
      let fileName = fileRow.name // 默认使用原始文件名

      // 尝试从Content-Disposition头中提取文件名
      if (contentDisposition) {
        // 首先尝试匹配 filename*=UTF-8'' 格式
        const utf8Match = contentDisposition.match(/filename\*=UTF-8''([^;]+)/i)
        if (utf8Match && utf8Match[1]) {
          try {
            fileName = decodeURIComponent(utf8Match[1])
          } catch (e) {}
        } else {
          // 如果没有UTF-8格式，尝试匹配普通filename格式
          const fileNameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
          if (fileNameMatch && fileNameMatch[1]) {
            let extractedName = fileNameMatch[1].replace(/['"]/g, '')

            // 处理可能的编码文件名
            if (extractedName.startsWith('UTF-8')) {
              const nestedUtf8Match = extractedName.match(/UTF-8''(.+)/)
              if (nestedUtf8Match && nestedUtf8Match[1]) {
                try {
                  fileName = decodeURIComponent(nestedUtf8Match[1])
                } catch (e) {}
              }
            } else {
              fileName = extractedName
            }
          }
        }
      }

      // 创建URL和a标签进行下载
      const url = window.URL.createObjectURL(new Blob([response.data]))
      const link = document.createElement('a')
      link.href = url

      // 设置文件名
      link.setAttribute('download', fileName)

      // 触发下载
      document.body.appendChild(link)
      link.click()

      // 清理
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)

      ElMessage.success('文件开始下载')
    } catch (error) {
      ElMessage.error('文件下载失败')
    } finally {
      loading.value = false
    }
  }

  // 删除文档
  const handleDelete = (row: DocumentItem) => {
    ElMessageBox.confirm('确定要删除该文档吗？', '提示', {
      type: 'warning',
    })
      .then(async () => {
        try {
          await deleteCaseDoc(row.id)
          // 清除缓存，避免获取到已删除的数据
          lawcaseStore.clearCaseDocDetailCache(row.id)
          ElMessage.success('删除成功')
          getDocumentList()
        } catch (error) {
          ElMessage.error('删除失败')
        }
      })
      .catch(() => {})
  }

  // 删除文档内的单个文件
  const handleFileDelete = (fileRow: FileItem) => {
    ElMessageBox.confirm('确定要删除该文件吗？', '提示', {
      type: 'warning',
    })
      .then(async () => {
        try {
          // 使用正确的API和参数格式：复数形式的ids并放在data中
          await deleteFileApi(fileRow.id.toString())
          ElMessage.success('文件删除成功')

          // 更新当前文档的文件列表
          if (currentDocument.value && currentDocument.value.file_list) {
            currentDocument.value.file_list = currentDocument.value.file_list.filter(
              file => file.id !== fileRow.id
            )
            currentDocument.value.file_count = currentDocument.value.file_list.length
          }

          // 刷新主列表
          getDocumentList()
        } catch (error) {
          ElMessage.error('文件删除失败')
        }
      })
      .catch(() => {})
  }

  // 提交表单
  const handleSubmit = () => {
    formRef.value.validate(async (valid: boolean) => {
      if (valid) {
        try {
          const formData = new FormData()
          formData.append('case_code', form.case_code)
          formData.append('title', form.title)
          formData.append('doc_type', form.doc_type)
          if (form.file) {
            formData.append('file', form.file)
          }

          await uploadCaseDoc(formData)
          // 上传成功后清除所有缓存，确保获取最新数据
          lawcaseStore.clearCaseDocDetailCache()
          ElMessage.success('上传成功')
          dialogVisible.value = false
          getDocumentList()
        } catch (error) {
          ElMessage.error('上传失败')
        }
      }
    })
  }

  // 初始化
  onMounted(() => {
    getDocumentList()
  })
</script>

<style scoped>
  .document-container {
    padding: 20px;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .document-card {
    margin-bottom: 20px;
  }

  .upload-demo {
    width: 100%;
  }

  .document-detail {
    padding: 0 20px;
  }

  .file-section {
    margin-top: 20px;
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }

  .section-header h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
  }

  .empty-file {
    margin-top: 20px;
  }

  .file-preview {
    max-height: 70vh;
    overflow: auto;
  }

  .preview-info {
    margin-bottom: 15px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
  }

  .preview-info p {
    margin: 5px 0;
  }

  .image-preview {
    text-align: center;
  }

  .no-preview {
    text-align: center;
    padding: 20px 0;
  }

  /* 文档详情抽屉样式 */
  :deep(.document-detail-drawer .el-drawer__header) {
    background: linear-gradient(90deg, #409eff 0%, #66b1ff 100%);
    color: #ffffff;
    margin-bottom: 0;
    padding: 15px 20px;
  }

  :deep(.document-detail-drawer .el-drawer__header .el-drawer__close-btn) {
    color: #ffffff;
  }

  :deep(.document-detail-drawer .el-drawer__title) {
    color: #ffffff;
  }

  /* 查看详情按钮样式 */
  .view-btn {
    background-color: #409eff;
    color: #ffffff;
    border-color: #409eff;
  }

  /* 文本预览样式 */
  .text-preview {
    padding: 10px 0;
  }

  .text-preview :deep(.el-textarea) {
    font-family: 'Courier New', monospace;
  }
</style>
